/**
 * Splash views
 * Created by Delicate on 2017/9/25.
 */
import React from 'react';
import {
    StyleSheet,
    Image,
    View,
    Animated,
    Text,
    TouchableOpacity,
    TouchableWithoutFeedback,
    StatusBar
} from 'react-native';
import {NavigationActions} from 'react-navigation';
import DeviceInfo from 'react-native-device-info'

import Constants from '../config/Constants'
import PassportService from '../services/Passport'
import SystemService from '../services/System'

let self = null, timer = null;

class Views extends React.Component {

    constructor(props) {
        super(props);
        self = this;
        this.state = {
            needUpdate: false,
            adOpacity: new Animated.Value(0),
            skipText: Constants.SPLASH_AD_WAIT_TIME,
            ad: {
                src: '',
                url: '',
                title: ''
            }
        }
    }

    componentWillMount() {

    }

    componentDidMount() {
        self.initUser();
        self.load();
    }

    componentWillUnmount() {
        if (timer) clearInterval(timer);
    }

    //从storage中加载token&user_name
    async initUser() {
        try {
            const ret = await PassportService.loadToken();
            user.token = ret.token;
            user.user_name = ret.user_name;
            user.loginState = true;
        } catch (err) {
            user.loginState = false;
        }
    }

    //加载更新&AD信息
    async load() {
        const {result, message, data} = await SystemService.splash();
        if (result) {
            const currentVersion = data.version;
            const localVersion = DeviceInfo.getVersion();
            const cacheVersion = await SystemService.getCacheVersion() || {};
            let update = {
                version: localVersion
            };
            let isFirst = false;
            if (currentVersion.version !== localVersion) {
                update = {
                    version: currentVersion.version,
                    content: currentVersion.version_log,
                    size: currentVersion.version_size,
                    url: currentVersion.upload_url
                }
            } else {
                if (cacheVersion.version !== localVersion) {
                    isFirst = currentVersion.open_guide === 1; // 1 = 打开guide
                    await SystemService.setCacheVersion({
                        version: localVersion
                    });
                }
            }
            global.config = {
                isFirst,
                update,
                version: localVersion
            };
            //等待开屏&判断是否显示广告
            setTimeout(() => {
                if (data.ad) {
                    self.setState({
                        ad: data.ad
                    })
                } else {
                    self.skip();
                }
            }, Constants.SPLASH_WAIT_TIME);
        } else {
            Toast.show(message);
            setTimeout(() => {
                self.skip();
            }, Constants.SPLASH_WAIT_TIME);
        }
    }

    //监听AD加载END
    adLoadEnd() {
        Animated.timing(self.state.adOpacity, {
            duration: 200,
            toValue: 1
        }).start(() => {
            timer = setInterval(() => {
                if (self.state.skipText > 1) {
                    self.setState({
                        skipText: self.state.skipText - 1
                    })
                } else {
                    self.setState({
                        skipText: '跳过'
                    });
                    clearInterval(timer);
                    self.skip();
                }
            }, 1000)
        });
    }

    reset(...route) {
        let actions = [];
        for (const item of route) {
            actions.push(NavigationActions.navigate(item))
        }
        const resetAction = NavigationActions.reset({
            index: route.length - 1,
            actions: actions
        })
        self.props.navigation.dispatch(resetAction);
    }

    skip(route) {
        //等待开屏效果完成
        if (global.config.isFirst) {
            self.reset({
                routeName: 'Guide',
                params: {
                    skipTo: {
                        routeName: route,
                        params: {
                            url: self.state.ad.url,
                            title: self.state.ad.title,
                            type: 'splash'
                        }
                    }
                }
            });
        } else {
            self.reset({
                routeName: 'Index',
                params: {
                    skipTo: {
                        routeName: route,
                        params: {
                            url: self.state.ad.url,
                            title: self.state.ad.title,
                            type: 'splash'
                        }
                    }
                }
            });
        }
    }

    render() {
        return (
            <View style={[base.columnCC, base.clientWH, styles.container]}>
                <StatusBar barStyle={'light-content'}/>
                <Image
                    style={base.clientWH}
                    source={require('../sources/image_global_splash.png')}
                    resizeMode={'stretch'}
                >
                    <TouchableWithoutFeedback onPress={() => {
                        if (timer) {
                            this.skip('AdWebView')
                        }
                    }}>
                        <Animated.View style={[base.columnCC, styles.adBox, {opacity: this.state.adOpacity}]}>
                            {
                                this.state.ad.src ?
                                    <Image
                                        style={styles.ad}
                                        onLoadEnd={() => this.adLoadEnd()}
                                        source={this.state.ad.src}
                                        resizeMode={'cover'}/> : <View/>
                            }
                        </Animated.View>
                    </TouchableWithoutFeedback>
                    <Animated.View style={[styles.skipBox, {opacity: this.state.adOpacity}]}>
                        <TouchableOpacity
                            onPress={() => this.skip()}
                            activeOpacity={layout.TOUCH_OPACITY_ACTIVE}>
                            <View style={[base.rowCC, styles.skip]}>
                                <Text allowFontScaling={false} style={styles.skipText}>{'跳过('+this.state.skipText+')'}</Text>
                            </View>
                        </TouchableOpacity>
                    </Animated.View>
                </Image>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#fff',
    },
    adBox: {
        alignSelf: 'stretch',
        height: layout.MAX_HEIGHT - layout.height(254),
        backgroundColor: '#fff'
    },
    ad: {
        flex: 1,
        alignSelf: 'stretch',
    },
    skipBox: {
        position: 'absolute',
        bottom: layout.GAP_VERTICAL_LARGE,
        right: layout.GAP_HORIZONTAL_LARGE,
    },
    skip: {
        width: layout.width(130),
        height: layout.height(60),
        borderRadius: layout.height(60),
        borderColor: '#c1c1bf',
        borderWidth: layout.LINE_WIDTH,
        backgroundColor: '#fff'
    },
    skipText: {
        color: '#c1c1bf',
        fontSize: layout.font(28)
    }
});

//路由
const Splash = {
    screen: Views,
    navigationOptions: {
        header: null
    },
    name: 'Splash',
    sign: false
};

export default Splash;